const express = require('express');
const sign = express.Router();
const connection = require("../config");
const jwt = require("jsonwebtoken")
const secretKey = 'no1'

// 用戶註冊接口
sign.post('/sign/register', (req,res) => {
    const {username, password} = req.body;
    let sql = `select * from user where username=?`;
    // 註冊失敗
    connection.query(sql,[username], function (err, result) {
        if (err) {
            console.log('[SELECT ERROR]:', err.message);
            return res.send({
                status: 0,
                msg: '註冊失敗'
            })
        }
        // 用戶名已存在
        if (result.length > 0) {
            res.send({
                status: 0,
                msg: '用戶名已存在！'
            })
        } else {
            const insertsql = `insert into user (username, password) values(?,?)`
            connection.query(insertsql, [username, password], (errs, results) => {
                if (errs) {
                    console.log('[SELECT ERROR]:', err.message);
                    return;

                }
                res.send({
                    status: 1,
                    msg: "用戶註冊成功，歡迎你去登錄！"
                })
            })
        }
        
    });
})

// 用戶登錄接口
sign.post('/sign/login', (req,res) => {
    const {username, password} = req.body;
    console.log(req, '============')
    let sql = `select * from user where username=? and  password=?`;
    // 登錄失敗
    connection.query(sql,[username, password], function (err, result) {
        if (err) {
            console.log('[SELECT ERROR]:', err.message);
            return res.send({
                status: 0,
                msg: '登錄失敗'
            })
        }
        console.log(result,0)
        if (result.length > 0) {
            // 登錄成功
            // 格式：jwt.sign({用戶信息},密鈅，token有效時長)
            let tokenStr = jwt.sign({username: username}, secretKey, { expiresIn: '8h' })
            res.send({
                status: 1,
                msg: '登錄成功',
                token: tokenStr,
                uid: result[0].id
            })
        } else {
            res.send({
                status:0,
                msg: '用戶名或密碼不正確'
            })
        }
        
    });
    
})

sign.post('/sign/modify', (req, res) => {
    const {username, password, repassword} = req.body;
    if (username && password && repassword) {
        if (password == repassword) {
            connection.query("update user set password=?, repassword=? where username=?",[password,repassword,username],(err,result)=>{
                if(err){
                    return "失败";
                }
                console.log(result);
                res.send({status: 1, msg: '密碼修改成功'});
            })
        } else {
            res.send({status: 0, msg: '兩次密碼輸入不一致'});
        }
    } else {
        res.send({status: 0, msg: '請輸入用戶名，密碼和確認密碼'});
    }
    
})

module.exports = sign;